﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pay.IService;
using Pay.Service;
using Pay.TO;
using Pay.DTO;
using Pay.Core;
using System.Net.Http;
using Flurl.Http;
using System.Threading.Tasks;

namespace Pay.Token.Controllers
{
    /// <summary>
    /// 消费
    /// </summary>
    [AppAuthorize("Member")]
    public class ConsumptionController : GeneralController
    {
        private readonly  IConsumeItemService _iConsumeItemService;
        private readonly IMerchantService _iMerchantService;
        private IAdvertisementService _iAdvertisementService;
        private readonly ISettingService _iSettingService;
        private IShippingAddressService _iShippingAddressService;
        private IMerchantBankCardService _iMerchantBankCardService;
        private IProductActivityService _iProductActivityService;
        public ConsumptionController(IConsumeItemService iConsumeItemService, IMerchantService iMerchantService, IAdvertisementService iAdvertisementService,
            ISettingService iSettingService, IShippingAddressService iShippingAddressService, IMerchantBankCardService iMerchantBankCardService,
            IProductActivityService iProductActivityService) {
            _iConsumeItemService = iConsumeItemService;
            _iMerchantService = iMerchantService;
            _iAdvertisementService = iAdvertisementService;
             _iSettingService = iSettingService;
            _iShippingAddressService = iShippingAddressService;
            _iMerchantBankCardService = iMerchantBankCardService;
            _iProductActivityService = iProductActivityService;
        }
        // GET: Consumption
        /// <summary>
        /// 消费首页
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public  async Task< ActionResult> Index()
        {
            ConsumeQuery cquery = new ConsumeQuery();
            cquery.merchant_id = UserId;
            var list = _iConsumeItemService.AppGetConsumeItemList(cquery);
#if !DEBUG
            if (!System.Web.HttpContext.Current.Request.Url.ToString().Contains(t_RequestMethod.token_url)) {
                list = list.Where(o => o.consume_type != (int)EConsumeItemType.DistributionMall && o.consume_type != (int)EConsumeItemType.BuyCourse).ToList();
            }
#endif
            merch_advertisement_query_type query = new merch_advertisement_query_type();
            query.position_type = (int)EAdvertisementPositionType.ConsumerPage;
            var ad = (_iAdvertisementService.AppGetAdvertisementList(query) ?? new List<ad_dto>()).FirstOrDefault();
            if (UserId > 0) {
                var member = _iMerchantService.Get(UserId);
                var log = new LogHelper("info");
                try {
                    var content = new Dictionary<string, string>();
                    content.Add("appId", RequestMethod.CAI_PIAO_APPID);
                    content.Add("accessToken", SecureHelper.MD5(RequestMethod.CAI_PIAO_APPID + RequestMethod.CAI_PIAO_SECRET_KEY));
                    content.Add("userTel", member.mobile);
                    var formUrlContent = new FormUrlEncodedContent(content);
                    var resultApi = await RequestMethod.CAI_PIAO_URL.PostAsync(formUrlContent).ReceiveString();
                    log.Info(resultApi);
                    var result = resultApi.ToObject<caipiao_res>();
                    if (result.code == 600) {
                        list.ForEach(s=> {
                            if (s.consume_type == 6) {
                                s.url = result.result.gl_url;
                            }
                        });
                    }  
                } catch (FlurlHttpException ex) {
                    log.Info(ex.Message);
                }
            }
            ViewData["consumeItemList"] = list;
            ViewData["ad"] = ad;
            ViewBag.img_url = RequestMethod.token_imgurl;
            ViewBag.user_id = UserId;
            return View();
        }


        /// <summary>
        /// 商品兑换
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult ProductExchange() {
            merch_advertisement_query_type query = new merch_advertisement_query_type();
            query.position_type = (int)EAdvertisementPositionType.ExchangeProduct;
            var ad = (_iAdvertisementService.AppGetAdvertisementList(query) ?? new List<ad_dto>()).FirstOrDefault();
            ViewData["ad"] = ad;
            ViewBag.img_url = RequestMethod.token_imgurl;
            return View();
        }
        /// <summary>
        /// 商品兑换列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public PartialViewResult _ProductExchange(ProductActivityQuery query) {
            ProductActivityQuery activityQuery = new ProductActivityQuery();
            activityQuery.ActivityType = EActivityType.ProductOnlyRedDrill;
            activityQuery.Time = DateTime.Now;
            activityQuery.page = query.page;
            activityQuery.size = query.size;
            var merchant = _iMerchantService.Get(t_RequestMethod.merchant_no);
            activityQuery.merchant_id = merchant.id;
            var list = _iProductActivityService.Gets(activityQuery);
            ViewBag.img_url = RequestMethod.token_imgurl;
            return PartialView(list);
        }



        #region 消费兑换（旧）
        ///// <summary>
        ///// 商品详情
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult ProductDetail(long id) {
        //    var model = _iConsumeItemService.AppGetComsumeProduct(id);
        //    ViewBag.img_url = RequestMethod.token_imgurl;
        //    return View(model);
        //}
        ///// <summary>
        ///// 确认兑换
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public ActionResult ConfirmExchange(long id, long? addressId) {
        //    shipping_address_dto address = null;
        //    if (addressId.GetValueOrDefault(0) > 0) {
        //        address = _iShippingAddressService.GetByAddressId(addressId.Value);
        //    } else {
        //        address = _iShippingAddressService.GetByDefault(UserId);
        //    }
        //    var model = _iConsumeItemService.AppGetComsumeProduct(id);
        //    ViewBag.img_url = RequestMethod.token_imgurl;
        //    ViewBag.address = address;
        //    ViewBag.BankCard = _iMerchantBankCardService.GetBankCardByMerchantId(UserId);
        //    return View(model);
        //}
        //[HttpPost]
        //public JsonResult Convert(long id, decimal reddrill, long? shipAddressId) {
        //    bool result = _iConsumeItemService.AppExchangeProduct(UserId, id, reddrill, shipAddressId);
        //    if (result) {
        //        return Json(ResultToJson.Json("兑换成功", true), JsonRequestBehavior.AllowGet);
        //    } else {
        //        return Json(ResultToJson.Json("兑换失败", false), JsonRequestBehavior.AllowGet);
        //    }
        //}
        /// <summary>
        /// 兑换记录
        /// </summary>
        /// <returns></returns>
        public ActionResult ExchangeRecord() {
            return View();
        }
        public PartialViewResult _ExchangeRecord(PageQuery query) {

            var list = _iConsumeItemService.AppGetUserExchangeProductHis(query, UserId);
            ViewBag.img_url = RequestMethod.token_imgurl;
            ViewBag.service_phone = _iSettingService.GetTokenSetting().app.service_phone;
            return PartialView(list);
        }
        ///// <summary>
        ///// 兑换成功
        ///// </summary>
        //public ActionResult Success() {
        //    return View();
        //}
        ///// <summary>
        ///// 兑换失败
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult Fail() {
        //    return View();
        //} 
        #endregion

    }
}